<template>
	<div class="user-info">

		<header class="header">
			<font-awesome-icon icon="arrow-left" class="back" @click="goBack" />
		</header>
		<main class="content">
			<!-- 头像 -->
			<section class="info-item avatar-section">
				<div class="title">
					<font-awesome-icon icon="camera" class="icon" />
					头像
				</div>
				<div class="avatar-upload">
					<label for="avatar-upload" class="value">
						<img  :src="avatarUrl" alt="Avatar" class="avatar" @tap="chooseFromAlbum"/>
					</label>
					<input id="avatar-upload" type="file" accept="image/*" @change="onAvatarChange"
						style="display: none;" capture="gallery" ref="fileInput" />
				</div>
			</section>
			<!-- 其他信息项 -->
			<section v-for="(item, index) in infoItems" :key="index" class="info-item" @click="handleClick(item)">
				<div class="title">
					<font-awesome-icon :icon="item.icon" class="icon" />
					{{ item.title }}
				</div>
				<input v-if="item.editing" v-model="item.value" :placeholder="item.placeholder" class="input-field" />
				<div v-else class="value">{{ item.value || item.placeholder }}</div>
			</section>
		</main>
		<footer class="footer">
			<button class="save-btn" @click="saveAll">绑定</button>
		</footer>
	</div>
</template>
<script>
	export default {
		data() {
			return {
				avatarUrl: '',
				avatarFile: null,
				infoItems: [{
						title: '昵称',
						icon: 'pen',
						value: '',
						placeholder: '请输入昵称',
						state: 'action',
						buttonText: '完善',
						editing: false
					},
					{
						title: '手机号',
						icon: 'phone',
						value: '',
						placeholder: '未填写',
						state: 'action',
						buttonText: '完善',
						editing: false
					}
				],
				showAddressModal: false,
				showAddressDetailModal: false,
				selectedProvince: '',
				selectedCity: '',
				selectedDistrict: '',
				detailedAddress: '',
				provinces: [],
				cities: [],
				districts: [],
				id: 0,
			};
		},
		mounted() {
			//在程序页面DOM加载之后就会执行的代码
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					const code = loginRes.code;
					// 发送 code 和用户信息到服务器进行绑定
					uni.request({
						url: 'http://zhaoyang.nat300.top/user/find', // 替换为你的服务器地址
						method: 'POST',
						data: {
							code: code, // 微信提供的临时登录凭证
						},
						header: {
							'content-type': 'application/json' // 设置请求头，默认值
						},
						success: (res) => {
							console.log(res.data)
							if (res.statusCode === 200 && res.data != 0) {
								let id = res.data;
								uni.navigateTo({
									url: `/pages/lucky/lucky?status=${id}`
								})
							} else {
								uni.showToast({
									title: '用户未绑定过',
									icon: 'none',
								});
							}
						},
						fail: () => {
							uni.showToast({
								title: '网络错误，请检查网络连接',
								icon: 'none'
							});
						}
					});
				},
				fail: (err) => {
					console.error('登录失败：', err);
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
				}
			});
		},
		methods: {
			chooseFromAlbum() {
			  // 从相册中选择图片作为头像
			  uni.chooseImage({
			    count: 1, // 只允许选择一张图片
			    sizeType: ['original', 'compressed'], // 可以选择原图或压缩后的图片
			    sourceType: ['album'], // 只能从相册选择
			    success: (res) => {
			      this.avatarUrl = res.tempFilePaths[0]; // 更新头像URL
			    }
			  });
			},
			goBack() {
				this.$router.back();
			},
			openGallery() {
				this.$refs.fileInput.click();
			},
			onAvatarChange(event) {
				const file = event.target.files[0];
				if (file) {
					if (file.size > 5 * 1024 * 1024) {
						alert('图片大小不能超过5MB');
						return;
					}

					const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
					if (!allowedTypes.includes(file.type)) {
						alert('请上传JPG、PNG或GIF格式的图片');
						return;
					}

					this.avatarFile = file;
					const reader = new FileReader();
					reader.onload = e => {
						this.avatarUrl = e.target.result;
					};
					reader.readAsDataURL(file);
				}
			},
			handleClick(item) {
				item.editing = true;
			},
			saveAll() {
				// 保存头像
				if (this.avatarFile) {
					// 这里可以添加上传头像到服务器的逻辑
					console.log('保存头像文件:', this.avatarFile);
				}

				// 保存其他信息项
				this.infoItems.forEach(item => {
					console.log(`保存${item.title}:`, item.value);
					item.editing = false;
				});
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						const code = loginRes.code;
						// 发送 code 和用户信息到服务器进行绑定
						uni.request({
							url: 'http://zhaoyang.nat300.top/user/login', // 替换为你的服务器地址
							method: 'POST',
							data: {
								code: code,
								nickname: this.infoItems[0].value,
								avatarUrl: this.avatarUrl,
							    phone: this.infoItems[1].value,
							},
							header: {
								'content-type': 'application/json' // 设置请求头，默认值
							},
							success: (res) => {
									this.id = res.data
									console.log('请求成功', res.data); // 后端返回的数据
									if (res.statusCode === 200 && res.data != 0) {
										uni.navigateTo({
											url: `/pages/lucky/lucky?status=${this.id}`
										})
									} else {
										uni.showToast({
											title: '绑定失败',
											icon: 'none',
										});
									}
							
								},
								fail(err) {
									console.error('请求失败', err);
								}
						});
					},
					fail: (err) => {
						console.error('登录失败：', err);
						uni.showToast({
							title: '登录失败，请重试',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style scoped>
	.user-info {
		font-family: Arial, sans-serif;
	}

	.header .back {
		margin-right: auto;
		cursor: pointer;
		font-size: 20px;
	}

	.icon {
		margin-right: 1px;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15px;
		background-color: #fff;
		border: 1px solid #ddd;
		margin-bottom: 10px;
	}

	.avatar-section {
		position: relative;
	}

	.avatar-upload {
		cursor: pointer;
	}

	.avatar {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		object-fit: cover;
	}

	.avatar-placeholder {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border: 2px dashed #ddd;
	}

	.upload-icon {
		font-size: 24px;
		color: #999;
		margin-bottom: 5px;
	}

	.title {
		color: black;
		font-weight: 800;
		flex-grow: 1;
	}

	.input-field {
		flex-grow: 1;
		padding: 5px;
		margin-left: 10px;
		border-radius: 4px;
	}

	.footer {
		padding: 20px;
		background-color: #fff;
		width: 90%;
		position: fixed;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
	}

	.save-btn {
		width: 90%;
		padding: 10px;
		background-color: rgb(119, 201, 75);
		color: #fff;
		border: none;
		border-radius: 50px;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		font-size: 16px;
	}
</style>